package com.ddz.implementation;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

import com.ddz.fightthelandlord.MainMenuState;
import com.ddz.interfaces.IFileIO;
import com.ddz.interfaces.IInput;

public abstract class GameBase extends Activity {

	Renderer mRenderView;
	Graphics mGraphics;
	Audio mAudio;
	IInput mInput;
	IFileIO mFileIO;
	GameStateManager mStateManager;
	WakeLock mWakeLock;
	Display mDisplay;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
		int frameBufferWidth = isPortrait ? 480 : 800;
		int frameBufferHeight = isPortrait ? 800 : 480;
		Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
				frameBufferHeight, Config.RGB_565);

		mDisplay = getWindowManager().getDefaultDisplay();

		float scaleX = (float) frameBufferWidth / mDisplay.getWidth();
		float scaleY = (float) frameBufferHeight / mDisplay.getHeight();

		mRenderView = new Renderer(this, frameBuffer);
		mGraphics = new Graphics(getAssets(), frameBuffer);
		mInput = new Input(this, mRenderView, scaleX, scaleY);
		mFileIO = new FileIO(this);
		mAudio = new Audio(this);
		mStateManager = GameStateManager.getInstance();
		mStateManager.pushState(new MainMenuState(this));
		setContentView(mRenderView);

		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
				"MyGame");
	}

	@Override
	public void onResume() {
		super.onResume();
		mWakeLock.acquire();
		mStateManager.getTopState().onResume();
		mRenderView.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		mWakeLock.release();
		mRenderView.onPause();
		mStateManager.getTopState().onResume();

		if (isFinishing())
			mStateManager.getTopState().dispose();
	}


	public Audio getAudio() {
		return mAudio;
	}

	public IInput getInput() {
		return mInput;
	}

	public IFileIO getFileIO() {
		return mFileIO;
	}

	public Graphics getGraphics() {
		return mGraphics;
	}

	public RectF getDisplayBounds() {
		return new RectF(0, 0, mDisplay.getWidth(),
				mDisplay.getHeight());
	}
}
